/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


/*************************************************************************
 * File: event_epoll.cpp
 *************************************************************************
 *\author: starlove
 *************************************************************************/

#ifndef __MLSE_PLATFORM_WIN__

#include <network/event_epoll.h>
#include <network/epoll.h>

#include <errno.h>

CEpollEventIO::CEpollEventIO()
    :m_handleEpoll(0)
{
    return;
}

CEpollEventIO::~CEpollEventIO()
{
    ::close(m_handleEpoll);
    m_handleEpoll = -1;
    m_epoll.Stop();
}

bool CEpollEventIO::Init(HANDLE handleEpoll)
{
    if(m_epoll.GetIOHandle())
        return false;
    m_epoll.SetIOHandle(handleEpoll);
    m_epoll.Start();
    return true;
}

bool CEpollEventIO::Init()
{
    return Init(0);
}

HANDLE CEpollEventIO::GetIOHandle()
{
    return m_epoll.GetIOHandle();
}

bool CEpollEventIO::Bind(EVHANDLE hd)
{
    return true;
}

LPEVENT CEpollEventIO::Query(unsigned int &ev_count, unsigned int time_out /* = INFINITE */)
{
    LPEVENT ev_l 				= NULL;
    LPEVENT ev 					= NULL;
    unsigned int ev_pop_count	= 0;
    unsigned long	s 			= GetTimestamp();
    unsigned long	t 			= GetTimestamp();

    while( (ev = m_epoll.PopEvent()) )
    {
        if(ev_pop_count >= ev_count || (GetTimestamp() - s) >= time_out)
            break;
        ev->next = ev_l;
        ev_l = ev;
        ev_pop_count ++;
    }

    unsigned long rt = GetTimestamp() - t;
    if( rt < 1 && ev_pop_count == 0)
    {
        usleep((1) * 1000);
		ev = NULL;
    }

    ev_count = ev_pop_count;
    return ev_l;
}

void CEpollEventIO::Post(LPEVENT ev)
{
}

#endif

